<?php

namespace App\Http\Controllers;


use AetherUpload\ConfigMapper;
use AetherUpload\Receiver;
use AetherUpload\RedisHandler;
use AetherUpload\Responser;
use AetherUpload\UploadHandler;

class UploadController extends UploadHandler
{
    private $receiver;
    public function __construct(Receiver $receiver)
    {
        \App::setLocale(request('locale'));
        $this->receiver = $receiver;
        ConfigMapper::getInstance()->applyGroupConfig(request('group'));
        $this->middleware(ConfigMapper::get('MIDDLEWARE_PREPROCESS'))->only('preprocess');
        $this->middleware(ConfigMapper::get('MIDDLEWARE_SAVE_CHUNK'))->only('saveChunk');
    }


    public function saveChunk()
    {
        $this->receiver->chunkTotalCount = request('chunk_total', 0);# 分片总数
        $this->receiver->chunkIndex = request('chunk_index', 0);# 当前分片号
        $this->receiver->uploadBaseName = request('upload_basename', 0);# 文件临时名
        $this->receiver->uploadExt = request('upload_ext', 0); # 文件扩展名
        $this->receiver->file = request()->file('file', 0);# 文件
        $subDir = request('sub_dir', 0);# 子目录名
        $this->receiver->uploadPartialFile = $this->receiver->getUploadPartialFilePath($subDir);
        $result = [
            'error'     => 0,
            'savedPath' => '',
            'chunkIndex' => $this->receiver->chunkIndex,
        ];
        $this->moveFile();
        if ( $this->receiver->chunkIndex === $this->receiver->chunkTotalCount ) {
            $result = $this->fileMerge();
        }
        return Responser::returnResult($result);
    }
    //判断是否是最后一块，如果是则进行文件合成并且删除文件块
    private function fileMerge() {
        $blob = '';
        for ($i = 1; $i <= $this->receiver->chunkTotalCount; $i++) {
            $blob .= file_get_contents($this->receiver->uploadPartialFile. '__' . $i);
        }
        file_put_contents($this->receiver->uploadPartialFile, $blob);
        $this->deleteFileBlob();  //删除快文件
        @unlink($this->receiver->uploadHead);
        if ( ! ($result['savedPath'] = $this->receiver->renameTempFile()) ) {
            return Responser::reportError(trans('aetherupload::messages.rename_file_fail'), true, $this->receiver->uploadHead, $this->receiver->uploadPartialFile);
        }
        RedisHandler::setOneHash(pathinfo($this->receiver->savedPath, PATHINFO_FILENAME), $this->receiver->savedPath);
        # 触发上传完成事件
        if ( ! empty($uploadCompleteEvent = ConfigMapper::get('EVENT_UPLOAD_COMPLETE')) ) {
            event(new $uploadCompleteEvent($this->receiver));
        }
        return $result;
    }
    //移动文件块
    private function moveFile() {
        $filename = $this->receiver->uploadPartialFile. '__' . $this->receiver->chunkIndex;
        move_uploaded_file($this->receiver->file->getRealPath(), $filename);
    }

    //删除文件块
    private function deleteFileBlob() {
        for ($i = 1; $i <= $this->receiver->chunkTotalCount; $i++) {
            @unlink($this->receiver->uploadPartialFile. '__' . $i);
        }
    }
}